//
//  ARPersonalPageViewModel.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/22.
//

import Foundation

class ARPersonalPageViewModel: ARWorkWaterFlowViewModelProvider {
    
    var dataSource: [ARWorkModel] = []
    var cellMoreActionType: ARWorkCollectionViewCell.MoreActionType = .more
    
    let userId: String
    var userModel: ARUserModel?
    
    init(userId: String) {
        self.userId = userId
    }
    
    /// 获取用户信息
    func fetchUser(_ completion: @escaping (Error?) -> Void) {
        do {
            try userModel = ARDataCenter.default.fetchUser(userId)
            ARHelper.afterAsyncInMainQueue {
                completion(nil)
            }
        } catch {
            completion(error)
        }
    }
    
    /// 获取workData
    func loadData(_ completion: @escaping (Error?) -> Void) {
        // 作品
        ARDataCenter.default.fetchUserAllWorkList(userId) { [weak self] workList, err in
            if let err = err {
                completion(err)
                return
            }
            guard let workList = workList else {
                completion(ARRequestError.modelConvertError(error: nil))
                return
            }
            
            ARHelper.afterAsyncInMainQueue {
                self?.dataSource.removeAll()
                self?.dataSource.append(contentsOf: workList)
                completion(nil)
            }
        }
    }
    
    /// 关注
    func followUser(completion: @escaping (Error?) -> Void) {
        // 因为 datacenter 获取的数据都是对象，所以在datacenter中修改之后，其他地方也会是最新的数据
        ARDataCenter.default.followOrUnfollowUser(userId, followOrUnfollow: true) { err in
            completion(err)
        }
    }
    
}
